package com.fangxing.configs;

import org.apache.commons.dbcp.BasicDataSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;

/**
 * Created by fangxing on 17-6-20.
 */
@Configuration
public class DatabaseConfig {
    private Logger logger = LoggerFactory.getLogger(DatabaseConfig.class);

    @Value("${datasource.driver}")
    static private String driver;
    @Value("${datasource.url}")
    static private String url;
    @Value("${datasource.username}")
    static private String username;
    @Value("${datasource.password}")
    static private String password;
    @Value("${datasource.maxActive}")
    static private int maxActive;
    @Value("${datasource.maxIdel}")
    static private int maxIdel;
    @Value("${datasource.maxWait}")
    static private long maxWait;

    static private DataSource dataSource;
    static public DataSource dataSource(){
        if (dataSource == null) {
            dataSource = buildDataSource();
        }
        return dataSource;
    }

    static DataSource buildDataSource(){
        BasicDataSource dataSource = new BasicDataSource();
        dataSource.setDriverClassName(driver);
        dataSource.setUrl(url);
        dataSource.setUsername(username);
        dataSource.setPassword(password);
        dataSource.setMaxActive(maxActive);
        dataSource.setMaxIdle(maxIdel);
        dataSource.setMaxWait(maxWait);
        dataSource.setValidationQuery("SELECT 1");
        dataSource.setTestOnBorrow(true);
        return dataSource;
    }

}
